import { inject, observer } from 'mobx-react';
import { routerShape } from 'react-router';
import { WeaTop, WeaTab, WeaLocaleProvider, WeaRightMenu, WeaReportGroup, WeaTools, WeaAlertPage } from 'ecCom';
import { WeaTableNew } from "comsMobx";
import * as mobx from "mobx";
import { Button, Modal, message } from 'antd';
import { Condition, getAdButtons } from './Condition';
import SaveAsModal from '../../public/wf-save-as-template';
import filter from 'lodash/filter';
import cloneDeep from 'lodash/cloneDeep';
import ColsetDialog from './ColsetDialog';
import map from 'lodash/map';

const WeaTable = WeaTableNew.WeaTable;
const getLabel = WeaLocaleProvider.getLabel;
const { ls } = WeaTools;

@inject('standardCustomReportStore')
@observer
export default class Main extends React.Component {
    static contextTypes = {
        router: routerShape
    }

    doInit(props) {
        const { standardCustomReportStore = {}, location } = props;
        const { getReportCondition } = standardCustomReportStore;
        getReportCondition(location.query);
    }

    componentDidMount() {
        const { standardCustomReportStore,location } = this.props;
        this.doInit(this.props);
        if(location.query.tabKey){
            standardCustomReportStore.setTabKey(location.query.tabKey);
        }
        this.clearworkflowidfornode();
    }

    componentDidUpdate() {
        const { standardCustomReportStore } = this.props;
        const { configs = {}, tabKey, title = '', doComponentDidUpdate = false, resetDoDidUpdate } = standardCustomReportStore;
        const currentConfig = configs[`key_${tabKey}`];
        if (currentConfig && doComponentDidUpdate) {
            this.report && this.report.update(mobx.toJS(currentConfig));
            resetDoDidUpdate();
        }
        if (typeof window.doThemeAction !== 'function' && document.title != title) document.title = title;
    }

    componentWillUnmount() {
        const { standardCustomReportStore } = this.props;
        standardCustomReportStore.clearDatas(true);
    }

    componentWillReceiveProps(nextProps) {
        if (this.props.location.key !== nextProps.location.key) {
            const { standardCustomReportStore } = this.props;
            standardCustomReportStore.clearAllStatus();
            this.doInit(nextProps);
        }
    }

    render() {
        const { standardCustomReportStore } = this.props;
        const { tableStore, loading, configs = {}, currentConfig = [], title, tabKey, topTab, modalVisible = false, noRight = false, renderComponent = '',colSetVisible } = standardCustomReportStore;
        const { switchTab } = standardCustomReportStore;
        const tabTitle = getLabel(20412, '自定义报表');
        const hasShowAll = this.hasShowAllCondition(currentConfig);
        //console.log(new Date().getTime(),"tabKey",tabKey,"configs",mobx.toJS(configs),"currentConfig",mobx.toJS(currentConfig));
        return (
            <div style={{ height: '100%', width: '100%' }}>
                {noRight ?
                    <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@by7nhq`}>
                        <div>
                            {getLabel(382663, '暂无权限')}
                        </div>
                    </WeaAlertPage>
                    :
                    <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@cvoa5e`}
                        collectParams={{ favname: title, favouritetype: '2' }}
                        datas={this.getRightMenu()}
                    >
                        <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@k5mwae`} loading={loading} icon={<i className='icon-coms-workflow' />} buttons={this.getButtons()}
                            iconBgcolor='#0079DE' title={title} showDropIcon={true}
                            dropMenuDatas={this.getRightMenu()}>
                            <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@rv1l3d`}
                                datas={mobx.toJS(topTab)}
                                keyParam="key"  //主键
                                onChange={(key) => {
                                    this.report && this.report.reset();
                                    this.report && this.report.setState({ showAll: true });
                                    switchTab(key);
                                }}

                                selectedKey={ tabKey }
                            />
                            <WeaReportGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaReportGroup@uc51u6`}
                                ref={report => this.report = report}
                                config={mobx.toJS(currentConfig)}
                                hasShowAll={hasShowAll}
                                onChange={this.doReportGroupChange.bind(this)}
                            />
                        </WeaTop>
                        <SaveAsModal ecId={`${this && this.props && this.props.ecId || ''}_SaveAsModal@cxlq9u`} ref={(saveAsModal) => this.saveAsModal = saveAsModal}
                            handleOk={(v) => this.saveTemplate({ 'moduleName': v, 'templateid': 0, 'frommodeid':tabKey })} />

                    {
                        colSetVisible ?  <ColsetDialog ecId={`${this && this.props && this.props.ecId || ''}_ColsetDialog@vf15qr`}  {...this.props} />: null
                    } 
                    </WeaRightMenu>
                }

            </div>
        )
    }

    dealValues() {
        const value = this.report.get();
        let checkArr = Object.keys(value).filter((item, index) => {
            if (value[item].checked) {
                return true;
            } else {
                return false;
            }
        });
        let conditionfieldids = checkArr.join(',');
        if (!conditionfieldids) {
            return {};
        }
        let params = {};
        checkArr.forEach((item, index) => {
            params = { ...params, ...value[item].value }
        })
        const {specialConditionValues= {}} = this.props.standardCustomReportStore;
        params.conditionfieldids = conditionfieldids;
        return {...params,...specialConditionValues};
    }

    doSearch() {
        const { standardCustomReportStore, location } = this.props;
        const { tabKey = 0 } = standardCustomReportStore;
        let params = this.dealValues();
        params['templateid'] = tabKey;
        let query = location.query;
        const { reportid } = query;
        const currentTime = new Date().getTime();
        const key = `${reportid}${currentTime}`;
        query['reportParamsKey'] = key;
        ls.set(key, params);
        this.context.router.push({
            pathname: "/main/workflow/standardCustomViewReportResult",
            query
        });
    }

    getButtons() {
        const { standardCustomReportStore } = this.props;
        const { tableStore, tabKey, saveTemplate, loading, setColSetVisible } = standardCustomReportStore;

        let btns = [];
        btns.push(
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ne46gs@search`} type="primary" disabled={loading} onClick={() => this.doSearch()}>{getLabel(197, '搜索')}</Button>),
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@w4onzc@reset`} type="primary" disabled={loading} onClick={() => this.reset()}>{getLabel(2022, '重置')}</Button>),
        )
        if (tabKey == 0) {
            btns.push(
                (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@vloien@saveAsModal`} type="primary" disabled={loading} onClick={() => { this.saveAsModal.click(true) }}>{getLabel(18418, '存为模板')}</Button>),
                (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@610qqx@colSet`} type="primary"disabled={loading} onClick={() => this.setColSetVisible(true)}>{getLabel(382660, '显示列定制')}</Button>),
            )
        } else {
            btns.push(
                (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@lupgl9@save`} type="primary" disabled={loading} onClick={() => this.saveTemplate()}>{getLabel(86, '保存')}</Button>),
                (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@oj74qs@saveAsModal`} type="primary" disabled={loading} onClick={() => this.saveAsModal.click(true)}>{getLabel(131623, '另存为')}</Button>),
                (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@yb44kq@delete`} type="primary" disabled={loading} onClick={() => this.deleteCondition()}>{getLabel(91, '删除')}</Button>),
                (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@spx6tj@colSet`} type="primary" disabled={loading} onClick={() => this.setColSetVisible(true)} >{getLabel(382660, '显示列定制')}</Button>),
            )
        }
        return btns;
    }

    getRightMenu() {
        const { standardCustomReportStore } = this.props;
        const { tabKey, saveTemplate, loading } = standardCustomReportStore;
        let btns = [];
        btns.push(
            {
                key: "search",
                icon: <i className="icon-coms-search" />,
                content: getLabel(197, '搜索'),
                disabled: loading,
                onClick: key => {
                    this.doSearch()
                }
            }, {
            key: "reset",
            icon: <i className="icon-coms-Reset" />,
            content: getLabel(2022, '重置'),
            disabled: loading,
            onClick: key => {
                this.reset();
            }
        }
        )

        if (tabKey == 0) {
            btns.push({
                key: "saveTemplate",
                icon: <i className="icon-coms-Journal-o" />,
                content: getLabel(18418, '存为模板'),
                disabled: loading,
                onClick: key => {
                    this.saveAsModal.click(true);
                }
            },
                {
                    key: "colSet",
                    icon: <i className='icon-workflow-Right-menu-Custom'/>,
                    content: getLabel(382660, '显示列定制'),
                    onClick: key => {
                        this.setColSetVisible(true);
                    }
                });
        } else {
            btns.push({
                key: "save",
                icon: <i className="icon-coms-Preservation" />,
                content: getLabel(86, '保存'),
                disabled: loading,
                onClick: key => {
                    this.saveTemplate();
                }
            }, {
                key: "saveAs",
                icon: <i className="icon-coms-Preservation" />,
                content: getLabel(131623, '另存为'),
                disabled: loading,
                onClick: key => {
                    this.saveAsModal.click(true);
                }
            }, {
                key: "delete",
                icon: <i className="icon-coms-form-delete" />,
                content: getLabel(91, '删除'),
                disabled: loading,
                onClick: key => {
                    this.deleteCondition();
                }
            },
                {
                    key: "colSet",
                    icon: <i className='icon-workflow-Right-menu-Custom'/>,
                    content: getLabel(382660, '显示列定制'),
                    onClick: key => {
                        this.setColSetVisible(true);
                    }
                })
        }
        btns.push({
            key: "back",
            icon: <i className="icon-coms-go-back" />,
            content: getLabel(383624, '返回'),
            disabled: loading,
            onClick: key => {
                this.goBack();
            }
        })
        return btns;
    }

    deleteCondition() {
        const { standardCustomReportStore } = this.props;
        const { deleteModule } = standardCustomReportStore;
        Modal.confirm({
            title: getLabel(131329, '信息确认'),
            content: getLabel(129890, '确定要删除吗？'),
            okText: getLabel(83446, '确定'),
            cancelText: getLabel(31129, '取消'),
            onOk() {
                deleteModule();
            },
        })
    }

    saveTemplate(params = {}) {
        const { templateid = '' } = params;
        if (templateid == 0) {
            this.report && this.report.setState({ showAll: true });
        }
        const { standardCustomReportStore } = this.props;
        const { saveTemplate } = standardCustomReportStore;
        let conditions = this.dealValues();
        saveTemplate({ ...conditions, ...params })
    }

    setColSetVisible(bool) {
        const { standardCustomReportStore,  } = this.props;
        const { setColSetVisible } = standardCustomReportStore;
        setColSetVisible(bool);
    }

    goBack() {
        const { standardCustomReportStore } = this.props;
        const { clearDatas } = standardCustomReportStore;
        clearDatas();
        this.context.router.push({
            pathname: "/main/workflow/standardCustomReportList",
        });
    }

    reset() {
        const { standardCustomReportStore } = this.props;
        let { tabKey = 0, loadConfig } = standardCustomReportStore;
        loadConfig(tabKey);
        this.report.setState({ showAll: true });
    }

    doReportGroupChange(v, ids, isFirst,valueMap) {
        this.doWorkflowConditionChange(v, ids, isFirst,valueMap);
    }

    //是否显示
    hasShowAllCondition(currentConfig = []) {
        if (currentConfig.length == 0) return false;
        let config = mobx.toJS(currentConfig);
        let configtemp = filter(config, (o = {}) => {
            const { isDefault = false, checked = false } = o;
            return isDefault || checked;
        })
        return config.length != configtemp.length;
    }

    //流程浏览框联动节点浏览框
    doWorkflowConditionChange(v, ids, isFirst,valueMap) {
        const { standardCustomReportStore } = this.props;
        const { configs = {}, tabKey, updateConfigItem ,setSpecialConditionValues } = standardCustomReportStore;
        const currentConfig = mobx.toJS(configs[`key_${tabKey}`]);
        if (currentConfig) {
            const configItem = currentConfig[ids];
            if (configItem && configItem.key === '-12') {
                const targetfieldid = '-13';
                for (let i = 0; i < currentConfig.length; i++) {
                    if (currentConfig[i].key === targetfieldid) {
                        let targetConfigItemconfig = currentConfig[i].config[0];
                        if (targetConfigItemconfig) {
                            let dataParams = targetConfigItemconfig.browserConditionParam.dataParams;
                            let completeParams = targetConfigItemconfig.browserConditionParam.completeParams;
                            targetConfigItemconfig.browserConditionParam.dataParams = {
                                ...dataParams,
                                'workflowid': v['field-12_value1']
                            };
                            targetConfigItemconfig.browserConditionParam.completeParams = {
                                ...completeParams,
                                'workflowid': v['field-12_value1']
                            };
                            updateConfigItem(i, 0, targetConfigItemconfig);
                            return;
                        }
                    }
                }

            }
            if(this.isSapBrowser(configItem) && valueMap){
                const id = configItem.key;
                const fieldid = "field" + id + "_value1";
                if(valueMap[fieldid]){
                    let valueObj = valueMap[fieldid].valueObj;
                    this.onSapBrowserChange(configItem,id,valueObj,(replaceDatas)=>{
                        let targetConfigItemconfig = configItem.config[1]
                        targetConfigItemconfig.browserConditionParam.replaceDatas=replaceDatas;
                        updateConfigItem(ids, 1, targetConfigItemconfig);
                        let updateParams  = {};
                        updateParams[`field${id}_value1`] = map(replaceDatas,"id").join(',');
                        setSpecialConditionValues(updateParams);
                    });

                }
            }
        }

    }

    clearworkflowidfornode() {
        const { standardCustomReportStore } = this.props;
        const { configs = {}, tabKey, updateConfigItem ,setSpecialConditionValues } = standardCustomReportStore;
        const currentConfig = mobx.toJS(configs[`key_${tabKey}`]);
        if (currentConfig) {

            for (let i = 0; i < currentConfig.length; i++) {
                if (currentConfig[i].key === '-13') {
                    let targetConfigItemconfig = currentConfig[i].config[0];
                    if (targetConfigItemconfig) {
                        targetConfigItemconfig.browserConditionParam.dataParams.workflowid = '';
                        targetConfigItemconfig.browserConditionParam.completeParams.workflowid = '';
                        return;
                    }
                }
            }

        }

    }


    isSapBrowser(configItem){
        if(configItem.config && configItem.config[1] && configItem.config[1].browserConditionParam && configItem.config[1].browserConditionParam.type==='226'){
            return true
        }
        return false;
    }

    onSapBrowserChange = (configItem,id, datas,callback) => {
        const dataParams = configItem.config[1].browserConditionParam.dataParams;
        let value;
        let params = {
            fromNodeorReport: "0",
            fieldid: id,
            fielddbtype: dataParams.fielddbtype,
            datas: JSON.stringify(datas),
        }
        WeaTools.callApi('/api/SapIntegration/browser/assignToBill', 'POST', params).then(result => {//[{}]
            const { datas = [] } = result;
            let replaceDatas  = [];
            if (datas.length == 0 || !datas[0]["field" + id] || !datas[0]["field" + id].specialobj || !datas[0]["field" + id].specialobj[0] || !datas[0]["field" + id].specialobj[0].id) {
            } else {
                const { specialobj = [{ name: "", id: "" }] } = datas[0]["field" + id];
                replaceDatas = specialobj;
            }
            callback(replaceDatas);
        });
    }
}